package site.wtcc.originalfavor.func.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

@Slf4j
public class JsonUtil {

    private static final ObjectMapper mapper;

    static {
        mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        mapper.registerModule(module);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
    }

    public static <T> Optional<String> toJson(T obj) {
        try {
            return Optional.of(mapper.writeValueAsString(obj));
        } catch (Exception ex) {
            return Optional.empty();
        }
    }

    public static <T> String toJson(T obj, String defaultValue) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (Exception ex) {
            return defaultValue;
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> Optional<T> fromJson(String json, Class<T> tClass) {
        try {
            if (tClass == String.class) {
                return Optional.of((T) json);
            }
            return Optional.of(mapper.readValue(json, tClass));
        } catch (Exception ex) {
            return Optional.empty();
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T fromJson(String json, Class<T> tClass, T defaultValue) {
        try {
            if (tClass == String.class) {
                return (T) json;
            }
            return mapper.readValue(json, tClass);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            return defaultValue;
        }
    }

    public static <T> T read(JsonNode json, Class<T> tClass) {
        if (json == null || json.isNull()) {
            return null;
        }
        return fromJson(json.asText(), tClass, null);
    }

    public static <T> T readFromJson(String mailInfoList, TypeReference<T> typeReference) {
        try {
            return mapper.readValue(mailInfoList, typeReference);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
        return null;
    }

    public static <T> T readFromJson(String mailInfoList, TypeReference<T> typeReference, T defaultValue) {
        try {
            return mapper.readValue(mailInfoList, typeReference);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
        return defaultValue;
    }
}
